const Koa = require( 'koa' );
const static = require( 'koa-static' );
const router = require( 'koa-router' )();
const views = require( 'koa-views' );

const convert = require( 'koa-convert' );
const bodyParser = require( 'koa-bodyparser' );
const path = require( 'path' );
const swig = require( 'swig' );

// let connectMultiparty = require( 'connect-multiparty' );

const config = require( './config' );
const appSetting = require( './setting' );

const authorize = require( './middlewares/authorize' );

const dashboard = require( './routes/dashboard' );
const account = require( './routes/account' );
const pages = require( './routes/pages' );
const user = require( './routes/user' );
const data = require('./routes/data');
const error = require( './routes/error' );


let app = new Koa();

appSetting.init();

app.use( bodyParser( {
    jsonLimit: '1mb',
    formLimit: '1mb'
} ) );

app.use( convert( static( 'static' ) ) );
app.use( views( path.join( __dirname, '/views' ), { map: { html: 'swig' } } ) );

router.use( error.routes(), error.allowedMethods() );
router.use( user.routes(), user.allowedMethods() );

app.use( authorize );

router.get( '/sign', async function ( ctx ) {
    return ctx.render( 'sign', {
        page: JSON.stringify(config.page)
    });
} );

router.use( '/account', account.routes(), account.allowedMethods() )
router.use( '/dashboard', dashboard.routes(), dashboard.allowedMethods() )
router.use( '/data', data.routes(), data.allowedMethods() )
router.use( pages.routes(), pages.allowedMethods() );

app.use( router.routes(), router.allowedMethods() );

let server = app.listen( config.port, function () {
    let host = server.address().address;
    let port = server.address().port;
    console.log( 'app listening at http://%s:%s', host, port );
} );


module.exports = app;
